<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-10-12
 * Time: 15:50:28
 * Info:
 */

namespace plugin\huiblog\app\model;

use think\Model;
use think\facade\Db;
use support\Cache;

class ArticleCate extends Model
{

    protected $table = 'blog_article_cate';

    /**
     * 自动时间戳类型
     * @var string
     */
    protected $autoWriteTimestamp = true;

    /**
     * 添加时间
     * @var string
     */
    protected $createTime = 'create_time';

    /**
     * 更新时间
     * @var string
     */
    protected $updateTime = 'update_time';

    /**
     * 默认是否显示全部
     */
    public function getPidMenuList($parentId = '0')
    {
        $where       = function ($query) use ($parentId) {
            if ( ! empty($parentId)) {
                $query->where('pid', $parentId);
            }
        };
        $list        = $this->field('id,pid,title')->where($where)->select();
        $pidMenuList = $this->buildPidMenu($parentId, $list->toArray());

        return $pidMenuList;
    }

    /**
     * 获取栏目总数量
     */
    public function count()
    {
        if (Cache::get('blogArticleCateCount')) {
            $count = Cache::get('blogArticleCateCount');
        } else {
            $count = Db::table($this->table)->count();
            Cache::set('blogArticleCateCount', $count);
        }

        return $count;
    }

    protected function buildPidMenu($pid, $list, $level = 0)
    {
        $newList = [];
        foreach ($list as $vo) {
            if ($vo['pid'] == $pid) {
                $level++;
                foreach ($newList as $v) {
                    if ($vo['pid'] == $v['pid'] && isset($v['level'])) {
                        $level = $v['level'];
                        break;
                    }
                }
                $vo['level'] = $level;
                if ($level > 1) {
                    $repeatString = "&nbsp;&nbsp;";
                    $markString   = str_repeat("{$repeatString}├{$repeatString}", $level - 1);
                    $vo['title']  = $markString.$vo['title'];
                }
                $newList[] = $vo;
                $childList = $this->buildPidMenu($vo['id'], $list, $level);
                ! empty($childList) && $newList = array_merge($newList, $childList);
            }

        }

        return $newList;
    }

    // 获取文章分类
    public function cates($order = 'sort asc')
    {
        if ($order != '') {
            $sort = $order;
        }
        $cates = ArticleCate::order($sort)->select()->toArray();
        foreach ($cates as $key => $value) {
            $cates[$key]['url']   = "/blog/lists?cate_id=".$value['id'];
            $cates[$key]['count'] = Db::table('blog_article')->where([
                'article_cate_id' => $value['id'],
                'status'          => 1
            ])->count();
        }

        return $cates;
    }

}
